$(document).ready(function () {




    layui.use(function () {

        initSubMenu();
        showRecordList();
        draw3DPie();
        queryTrainScore();
        photoWall();
        drawGun();


        var timer = setInterval(() => {
            drawGun();
        }, 30000);

    });




    // 指针
    const body = document.querySelector("body");
    const element2 = document.getElementById("g-pointer");
    const halfAlementWidth2 = element2.offsetWidth / 2;

    // 该变量用于跟踪鼠标是否悬停在具有类名为 .g-animation 的元素上
    let isHovering = false;

    // 判断元素是否悬停在具有类名为 .g-animation 的元素上
    window.addEventListener("mouseover", (event) => {
        const target = event.target;

        if (target.classList.contains("g-animation")) {
            isHovering = true;

            const rect = target.getBoundingClientRect();
            const style = window.getComputedStyle(target);

            element2.style.width = `${rect.width + 10}px`;
            element2.style.height = `${rect.height + 10}px`;
            element2.style.borderRadius = `0.04rem`;
            element2.style.transform = `translate(${rect.left - 5}px, ${rect.top - 5
                }px)`;
        }
    });

    // 判断元素是否离开在具有类名为 .g-animation 的元素上
    window.addEventListener("mouseout", (event) => {
        const target = event.target;
        if (target.classList.contains("g-animation")) {
            isHovering = false;

            // 样式复原
            element2.style.width = `0.32rem`;
            element2.style.height = `0.32rem`;
            element2.style.borderRadius = `50%`;
        }
    });

    // 用于控制两个鼠标指针元素
    body.addEventListener("mousemove", (e) => {
        window.requestAnimationFrame(function () {
            setPosition(e.clientX, e.clientY);

        });
    });

    function setPosition(x, y) {
        window.requestAnimationFrame(function () {

            if (!isHovering) {
                element2.style.transform = `translate(${x - halfAlementWidth2}px, ${y - halfAlementWidth2
                    }px)`;
            }
        });
    }



})



// 滚动列表
function showRecordList() {

    new AjaxChain()
        .setUrl('/train/score/list?pageNum=1&pageSize=12')

        .then(res => {

            var data = [];
            res.data.forEach((element, index) => {

                if (index % 2 != 0) {
                    var className = ''
                } else {
                    var className = 'box-inside'
                }

                data.push(` <div class="${className}">
                            <img src="../static/img/index/r${element.trainResult}.png" alt="">
                            <div>
                                <li>${element.projectName}</li>
                                <li>${element.trainType == 3 ? ("队伍名称：" + element.teamName) : ("人员名称：" + element.personName)}</li>
                                <li>用时：${element.useTime}s</li>
                                <li>${element.dataTime}</li>
                            </div>
                        </div>`)
                $(".pb").empty().append(data)


            });


        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();



    // new AjaxChain()
    //     .setUrl('/person/list?pageNum=1&pageSize=1')

    //     .then(res => {

    //         $('#fireman-count').empty().append(
    //             `${res.total}<span>人</span>`
    //         )

    //     })
    //     .catch(err => {
    //         console.error('请求异常:', err);
    //     })
    //     .send();
}


// 3d饼图

function draw3DPie() {

    new AjaxChain()
        .setUrl('/train/score/person/pass/total/count')
        .then(data => {
            var chart;
            var legend;
            var chartData = [

                {
                    "country": "未通过",
                    "value": (data.totalCount - data.totalPass)
                },
                {
                    "country": "合格次数",
                    "value": data.totalPass,
                }
            ];

            chart = new AmCharts.AmPieChart();
            chart.title = "";
            chart.labelText = "[[value]]次<br>[[title]]";
            chart.dataProvider = chartData;
            chart.titleField = "country";
            chart.colors = ['#00A8FF', '#00D7E9'];
            chart.valueField = "value";
            chart.labelTickColor = "#fff";
            chart.outlineColor = "#000";
            chart.outlineAlpha = 0.1;
            chart.outlineThickness = 1;
            chart.depth3D = 10;
            chart.angle = 45;

            chart.write("chart2-3d");


            monthTrainScore(data)


        })
        .send()

}

// 本月合格率

function monthTrainScore(data) {

    $('.center-chart-conut').empty().append(
        `
        <div class="center-conut-item index-card">
            <span>${data.totalCount || '-'}</span>
            <span>训练次数</span>
        </div>
        <div class="center-conut-item index-card">
            <span>${data.totalPass || '-'}</span>
            <span>训练合格次数</span>
        </div>
        <div class="center-conut-item index-card">
            <span>${data.totalRate || '-'}</span>
            <span>训练合格率</span>
        </div>
        `
    )


    // 获取所有卡片元素
    const cards = document.querySelectorAll('.index-card');
    let currentIndex = 0;

    function switchActiveCard() {
        // 移除所有激活状态
        cards.forEach(card => card.classList.remove('active'));

        // 添加当前激活状态
        cards[currentIndex].classList.add('active');

        // 更新索引（循环）
        currentIndex = (currentIndex + 1) % cards.length;
    }

    // 初始化立即激活第一个卡片
    cards[0].classList.add('active');

    // 启动定时器（10秒切换一次）
    setInterval(switchActiveCard, 5000);


}




// 各项目合格率

function queryTrainScore() {

    new AjaxChain()
        .setUrl('/train/score/person/best/count')
        .setData(
            JSON.stringify(
                {}
            )
        )
        .setMethod('post')
        .then(data => {

            trainScoreChart(data);

            $('.chart2-top')
                .empty()
                .append(
                    data.reduce((x, y) => {

                        let temp = new ST().project(1).find(function (activity) {
                            return activity.type === y.trainType;
                        });

                        return x + `<div class="chart2-top-item">
                                        <div class="item-image" style='background-image: url("../static/img/index/i${y.trainType}.png");'></div>
                                        <div>
                                            <span>${y.total == 0 ? '-' : ((y.total - y.fail) / (y.total) * 100).toFixed(0) + '%'}</span>
                                            <div>${temp.name}</div>
                                        </div>
                                    </div>`
                    }, '')
                )
            $('.center-chart-total')
                .empty()
                .append(
                    // 生成HTML字符串
                    [
                        `<div class="center-total-item">${data.slice(0, 3).map(v => {
                            let temp = new ST().project(1).find(function (activity) {
                                return activity.type === v.trainType;
                            });
                            return `<div style='background-image: url("../static/img/index/icon${v.trainType}.png");'><div>${temp.name}</div>
                            <span>${v.total}次</span>
                            </div>`
                        }).join('')}</div>`,
                        `<div class="center-total-item">${data.slice(3, 6).map(v => {
                            let temp = new ST().project(1).find(function (activity) {
                                return activity.type === v.trainType;
                            });
                            return `<div style='background-image: url("../static/img/index/icon${v.trainType}.png");'><div>${temp.name}</div>
                            <span>${v.total}次</span>
                            </div>`
                        }).join('')}</div>`
                    ].join('')
                )


            // 元素集合和状态存储
            // const $divs = $('.center-total-item>div')
            // let currentIndex = 0
            // let timeoutId = null

            // const activateNext = () => {
            //     // 清空所有激活状态
            //     $divs.addClass('active')

            //     // 如果是最后一个元素的特殊处理
            //     if (currentIndex === $divs.length - 1) {
            //         // 激活最后一个元素
            //         $divs.eq(currentIndex).removeClass('active')

            //         // 10秒后移除激活
            //         timeoutId = setTimeout(() => {
            //             $divs.removeClass('active')

            //             // 30秒后重置循环
            //             timeoutId = setTimeout(() => {
            //                 currentIndex = 0
            //                 activateNext()
            //             }, 10000)
            //         }, 3000)
            //     }
            //     // 常规元素处理
            //     else {
            //         // 激活当前元素
            //         $divs.eq(currentIndex).removeClass('active')

            //         // 10秒后切换下一个
            //         timeoutId = setTimeout(() => {
            //             currentIndex++
            //             activateNext()
            //         }, 3000)
            //     }
            // }

            // // 启动循环
            // timeoutId = setTimeout(() => {
            //     activateNext()
            // }, 10000);

            // // 清理定时器 (可选)
            // $(window).on('beforeunload', () => {
            //     clearTimeout(timeoutId)
            // })


            $('.center-total-item>div').mouseenter(function () {
                $('.center-total-item>div').addClass('active');
                $(this).removeClass('active');
            });
            $('.center-total-item>div').mouseleave(function () {
                $('.center-total-item>div').removeClass('active');
            });

        })
        .send();
}



// 照片墙

function photoWall() {
    new AjaxChain()
        .setUrl('/train/score/person/train/num/count')
        .setData(
            JSON.stringify(
                {
                    type: 4,
                    day: 30
                }
            )
        )
        .setMethod('post')
        .then(data => {


            $('#container')
                .empty()
                .append()
                .append(
                    data.reduce(
                        (x, y, index) => {
                            return x + `<div class='rotate-item chart-border'>
                                    <img class="subscript" src="../static/img/index/h${index + 1}.png" alt="">
                                    <img src="${y.photoPath ? ('/images/' + y.photoPath) : '../static/img/photo.png'}">
                                    <div>
                                        <li>姓名：${y.personName}</li>
                                        <li>次数：${y.trainNum}</li>
                                    </div>
                                </div>`

                        }, '')
                )

        })
        .send();

}


// 枪炮协同切换

var curChartType = 1;
$('.chart2-switch>span').click(function (e) {
    $(e.currentTarget).addClass('active').siblings().removeClass('active');

    curChartType = $(e.currentTarget).data().type;
    drawGun()

})

// 枪炮协同图表
var gunChart = null;
function drawGun() {

    new AjaxChain()
        .setUrl('/train/score/list?pageNum=1&pageSize=1&trainType=3')
        .then(lastTradinData => {

            $('.chart3-score').empty()
                .append(`<span>本次训练最终成绩：${lastTradinData.data[0].useTime}秒 </span> 开始时间：${lastTradinData.data[0].beginTime} - 结束时间：${lastTradinData.data[0].endTime}`)

            new AjaxChain()
                .setUrl('/train/score/teamtrain/detail')
                .setData(
                    { uuid: lastTradinData.data[0].trainUuid }
                )
                .then(data => {

                    var persons = [
                    ];
                    var chartData = [['useTime', 'distance', 'personName']]


                    if (curChartType == 1) {

                        $.each(data, function (e, i) {
                            persons.push((i.personName+'（'+i.seqNo+'）') + ',' + i.photoPath)

                            i.uwbScoreList.forEach(element => {


                                chartData.push([element.distance, element.useTime, (i.personName+'（'+i.seqNo+'）')])

                            });
                        })


                    } else {

                        $.each(data, function (e, i) {
                            persons.push((i.personName+'（'+i.seqNo+'）') + ',' + i.photoPath)

                            i.uwbScoreList.forEach(element => {


                                chartData.push([element.useTime, element.distance, (i.personName+'（'+i.seqNo+'）')])

                            });
                        })

                    }

                    // chartData.sort((a, b) => a[0] - b[0]);



                    const datasetWithFilters = [];
                    const seriesList = [];
                    echarts.util.each(persons, function (personMsg) {

                        let [personName, photoPath] = personMsg.split(',')

                        var datasetId = 'dataset_' + personName;
                        datasetWithFilters.push({
                            id: datasetId,
                            fromDatasetId: 'dataset_raw',
                            transform: {
                                type: 'filter',
                                config: {
                                    and: [
                                        { dimension: 'useTime', gte: 0 },
                                        { dimension: 'personName', '=': personName }
                                    ]
                                }
                            }
                        });
                        seriesList.push({
                            type: 'line',
                            datasetId: datasetId,
                            lineStyle: {
                                shadowColor: 'rgba(0, 0, 0, 0.9)',
                                shadowBlur: 3,
                                shadowOffsetX: 3,
                                shadowOffsetY: 2,
                            },
                            showSymbol: false,
                            name: personName,
                            endLabel: {
                                show: true,
                                color: '#ddd',
                                formatter: function (params) {
                                    return params.value[2] + ': ' + params.value[1] + (curChartType != 1 ? "米" : "秒");
                                }
                            },
                            labelLayout: {
                                moveOverlap: 'shiftY'
                            },
                            emphasis: {
                                focus: 'series'
                            },
                            encode: {
                                x: 'useTime',
                                y: 'distance',
                                label: ['personName', 'distance'],
                                itemName: 'useTime',
                                tooltip: ['distance']
                            }
                            // , markPoint: {
                            //     symbol: 'pin',

                            //     symbol: `image://${'/images/' + photoPath}`,
                            //     symbolSize: [40, 40],
                            //     symbolOffset: [0, -20],
                            //     label: {
                            //         show: true, // 开启显示
                            //         position: 'inside', // 在上方显示
                            //         formatter: personName,
                            //         // textStyle: { // 数值样式
                            //         //   color: '#22b8ed',
                            //         //   fontSize: 16
                            //         // },
                            //         // color: '#fff',
                            //         // backgroundColor: '#36a3f7',
                            //         // borderRadius: 4,
                            //         // padding: [4, 8]
                            //     }
                            //     ,
                            //     data: []
                            // }
                        });
                    });
                    var option = {
                        animationDuration: 10000,
                        dataset: [
                            {
                                id: 'dataset_raw',
                                source: chartData
                            },
                            ...datasetWithFilters
                        ],
                        tooltip: {
                            order: 'valueDesc',
                            trigger: 'axis'
                        },
                        xAxis: {
                            type: 'value',
                            name: curChartType == 1 ? '行进距离（米）' : '耗时',
                            axisTick: {
                                show: false,
                            },
                            splitLine: {
                                show: false,
                                lineStyle: {
                                    color: '#A8A8A822',
                                }
                            }
                        },
                        yAxis: {
                            name: curChartType == 1 ? '耗时' : '行进距离（米）',
                            axisTick: {
                                show: false,
                            },
                            splitLine: {
                                show: false
                            }
                        },
                        grid: {
                            right: "7%",
                            top: "20%",
                            left: "10%",
                            bottom: "10%"
                        },
                        // dataZoom: [{
                        //     type: 'inside',
                        //     start: chartData[1].useTime,
                        //     end: chartData[chartData.length - 1].useTime
                        // }, {
                        //     show: true,
                        //     type: 'slider',
                        //     y: '90%',
                        //     start: chartData[1].useTime,
                        //     end: chartData[chartData.length - 1].useTime
                        // }],
                        series: seriesList
                    };

                    if (gunChart) {
                        gunChart.dispose();
                        gunChart = null;
                    }
                    gunChart = echarts.init(document.getElementById('chart3'));

                    gunChart.setOption(option);

                })
                .send();



        }
        ).send()

}



// 训练成绩

function trainScoreChart(res) {

    let dateArr = [], minArr = [], avgArr = []


    res.forEach(element => {

        let temp = new ST().project(1).find(function (activity) {
            return activity.type === element.trainType;
        });

        dateArr.push(temp.name)
        minArr.push(element.minTime)
        avgArr.push(element.avgTime)


    });

    var option = {
        grid: {
            left: '25%',
            right: '10%',
            top: "15%",
            bottom: "5%",
        },
        legend: {
            show: true,
            itemWidth: 10,
            itemHeight: 10,
            // itemGap:50,
            left: "5%",
            top: "3%",
            textStyle: {
                color: '#fff',
                fontSize: 12
            }
        },
        "xAxis": {
            type: 'value',
            // "max": max,
            show: false,

            "splitLine": {
                "show": true,
                lineStyle: {
                    color: "#232e32"
                }
            },
            "axisLine": {
                "show": false
            },
            "axisLabel": {
                "show": true,
                "textStyle": {
                    "color": "#fff",
                    "fontSize": 12
                }
            },
            "axisTick": {
                "show": false
            }
        },
        "yAxis": [{
            "type": "category",
            "inverse": true,
            "data": dateArr,
            "axisLine": {
                "show": false
            },
            "axisTick": {
                "show": false
            },
            "axisLabel": {
                // "margin": 10,
                "textStyle": {
                    "color": "rgba(213, 225, 223, 1)",
                    "fontSize": 12
                }
            }
        }],
        "series": [{ //内
            type: 'bar',
            barWidth: 10,
            barGap: 1,
            name: '最好成绩',
            label: {
                show: true,
                position: 'right',
                textStyle: {
                    color: "rgba(61, 252, 205)",
                    fontSize: 12,
                    padding: [0, 10],
                },
                formatter: function (p) {

                    return p.value + '秒'
                }
            },
            legendHoverLink: false,
            silent: true,
            itemStyle: {
                borderColor: "#37D6AF",
                color: "rgba(61, 252, 205, 0.32)"
            },
            data: minArr
        },
        { //内2
            type: 'bar',
            barWidth: 10,
            name: '平均成绩',
            legendHoverLink: false,
            silent: true,
            label: {
                show: true,
                position: 'right',
                textStyle: {
                    color: "rgba(35, 185, 255)",
                    padding: [0, 10],
                    fontSize: 12,
                },
                formatter: function (p) {

                    return p.value + '秒'
                }
            },
            itemStyle: {
                borderColor: "#23B9FF",
                color: "rgba(35, 185, 255, 0.32)"
            },
            data: avgArr
        }
        ]
    };

    var myChart = echarts.init(document.getElementById('chart4-bottom'));

    myChart.setOption(option);
}



